$(function(){
  var bookid = getSearchValue("bookid","pageparam_edit");
  var bookname = getSearchValue("bookname","pageparam_edit");
  var orderid = getSearchValue("orderid","pageparam_edit") || 0;
  var publishid = getSearchValue("publishid","pageparam_edit") || "0";
  var publishbookid = getSearchValue("publishbookid","pageparam_edit") || "";
  var chapterid = getSearchValue("chapterid","pageparam_edit") || "";
  var chaptername = decodeURIComponent(getSearchValue("chaptername","pageparam_edit"));
  chaptername == "undefined" ? chaptername = "添加章节" : "";
  var wordCount;
  var editNum;
  var releaseTime;
  var chapterTle = $("#chapter-tle");
  var chapterCon = $("#chapter-con");
  var tws = $(".totalewords-on");
  var price = 0;
  var editMark = localStorage.getItem("edit_mark");
  if(editMark){
    chaptername = decodeURIComponent(getSearchValue("chaptername","record_edit_param"));
  }

  checkLog();
  createBarBread([{title:"首页",url:indexUrl},
    {title:"我的小说",url:"mybook-list.html"},
    {title:bookname,url:"mybook-detail.html",urlparam:"bookid=" + bookid + "&bookname=" + bookname+"&publishbookid="+publishbookid},
    {title:chaptername}]);
  loadGuide();
  if(chapterid){
    getChapterCon();
  }
  $.datetimepicker.setLocale('ch');
  function getChapterCon(){
    baseLoad();
    $.ajax({
      url:APIURL + "/Novel/getNovelChapterContentWeb.php",
      data:"userId=" + userId() + "&id=" + chapterid,
      success:function(data){
        hideBaseLoad();    
        data = $.parseJSON(data);
        if(data.status != "FAILED"){
          var tle = decodeURIComponent(data.value.title);
          var con = decodeURIComponent(data.value.content);
          if(editMark){
            tle = decodeURIComponent(localStorage.getItem("record_tle"));
            con = decodeURIComponent(localStorage.getItem("record_con"));
          }
          localStorage.removeItem("edit_mark");
          chapterTle.val(tle);
          chapterCon.val(con);
          changeWordsNum(data.value.wordCount);
          showDel();
          if(publishid && publishid != "0"){
            getReleaseNum(true)
          }
        }else{
          layer.open({
              content: data.value,
              time: 1
          }); 
        }
      },
      error:function(err){
        hideBaseLoad();
        layer.open({
            content: err.value || err_txt,
            time: 2
        });          
      }
    })
  }

  function showDel(){
    $("#cp-del").removeClass("hide");
  }

  //获取可发布次数
  function getReleaseNum(tip){
    if(tips){
      baseLoad();      
    }
    $.ajax({
      url:APIURL + "/BestNovel/getChapterReadCount2.php",
      data:"userId=" + userId() + "&chapterId=" + publishid,
      success:function(data){
        if(tips){
          hideBaseLoad();          
        }
        data = $.parseJSON(data);
        if(data.status != "FAILED"){
          changeEditNum(data.value.editCount);
        }else{
          if(tip){
            layer.open({
                content: data.value,
                time: 1
            });             
          }

        }

      },
      error:function(err){
        if(tips){
          hideBaseLoad();
          layer.open({
              content: err.value || err_txt,
              time: 2
          });          
        }
      }
    })
  }

  //更新可发布次数
  function changeEditNum(num){
    editNum = num;
    $(".edit-tipcon").removeClass("hide").find("em").text(num)
  }
  //更新字数
  function changeWordsNum(num){
    wordCount = num;
    $(".totalword-num").text(num);
  }
  //统计字数
	tws.on("focus",function(){
		IVL_TOTALWORDS = setInterval(function(){
      countWords()
		},200)
	}).on("blur",function(){
		clearInterval(IVL_TOTALWORDS);
	});

  function countWords(){
    var totalStr = "";
    var wordsNum;
    tws.each(function(){
      totalStr += $(this).val();
    });
    wordsNum = totalStr.replace("\r\n", "").replace("\n", "").replace(/\s/g,"").replace("\t", "").replace("　", "").length;
    changeWordsNum(wordsNum);
    return wordsNum;
  }

  var popView = $(".pop-view");
  var popViewTle = $(".pop-view .pop-view-tle");
  var popViewCon = $("#pop-view-txt");
  popView.on("click",function(){
    hidePopView();
  }).find(".pop-view-con").on("click",function(){
    return false
  })

  $("#cp-view").on("click",function(){
    popViewTle.text(tws.eq(0).val());
    popViewCon.val(tws.eq(1).val());
    popView.show();
  })

  //ESC键关闭预览
  $(document).on("keyup",function(e){
    if(e.keyCode == 27){
      hidePopView();
    }
  });

  function hidePopView(){
    popView.hide();
    popViewTle.text("");
    popViewCon.val("");
  };

  //添加，保存章节
  $("#cp-save").on("click",function(){
    var upserver = "/Novel/createNovelChapterWeb.php";
    var tle = encodeURIComponent($.trim(chapterTle.val()));
    var con = encodeURIComponent($.trim(chapterCon.val()));
    if(tle == ""){
      layer.open({
          content: '请输入章节标题',
          time: 1
      });
      return
    }
    if(con == ""){
      layer.open({
          content: '请输入章节内容',
          time: 1
      });
      return
    }
    if(chapterid){
      upserver = "/Novel/updateNovelChapter.php"
    }
    if(chapterid){
      layer.open({
          title: '提示',
          content: '备份将覆盖以前备份的内容,您确定要备份吗?',
          btn: ['嗯', '不要'],
          yes: function(index){
            layer.close(index);
            saveChapter();
          }
      })      
    }else{
      saveChapter(function(){
        getReleaseNum()
      });

    }
    function saveChapter(callback){
      var updata = "userId=" + userId() + "&bookId=" + bookid + "&remoteId=" + chapterid + '&orderId=' + orderid + '&publishId=' + publishid + "&title=" + tle + "&content=" + con + "&wordCount=" + wordCount;
      baseLoad();
      $.ajax({
        url:APIURL + upserver,
        data:updata,
        type:"post",
        success:function(data){
          data = $.parseJSON(data); 
          hideBaseLoad();
          if(data.status != "FAILED"){
            var tiptxt = "已备份章节";
            layer.open({
                content: tiptxt,
                time: 1
            });
            if(!chapterid){
              showDel();
              orderid = data.orderId;
              chapterid = data.value;      
            } 
            $(".bar-bread span").text(decodeURLComponent(tle));   
            callback && callback();  
          }else{
            layer.open({
                content: data.value,
                time: 1
            }); 
          }
        },
        error:function(err){
          hideBaseLoad();
          layer.open({
              content: err.value || err_txt,
              time: 2
          });
        }
      })      
    }


  })

  //删除章节
  $("#cp-del").on("click",function(){
    var self = this;
    layer.open({
        title: '提示',
        content: '您确定要删除本章节吗？',
        btn: ['嗯', '不要'],
        yes: function(index){
          baseLoad();
          $.ajax({
            url:APIURL + "/Novel/deleteBPChapter.php",
            data:"userId=" + userId() + '&remoteId=' + chapterid + '&publishId=' + publishid,
            type:"get",
            success:function(data){
              hideBaseLoad();
              data = $.parseJSON(data);
              if(data.status != "FAILED"){
                layer.open({
                    content: "删除成功",
                    time: 1,
                    end:function(){
                      localStorage.setItem("pageparam_detail","bookid="+bookid+"&bookname="+bookname+"&publishbookid=" + publishbookid);
                      window.location.href = "mybook-detail.html";
                    }
                });                
              }else{
                layer.open({
                    content: data.value,
                    time: 1
                }); 
              }

            },
            error:function(err){
              hideBaseLoad();
              layer.open({
                  content: err.value || err_txt,
                  time: 2
              });
            }
          })
          layer.close(index);
        }
    });

  });

  //发布到书城
  $("#cp-release").on("click",function(){
    var tle = $.trim(chapterTle.val());
    var con = $.trim(chapterCon.val());
    if(tle == ""){
      layer.open({
          content: '请输入章节标题',
          time: 1
      });
      return
    }
    if(con == ""){
      layer.open({
          content: '请输入章节内容',
          time: 1
      });
      return
    }
    // if(!chapterid){
    //   layer.open({
    //       content: "请先备份此章节",
    //       time: 1
    //   }); 
    //   return;
    // }
    if(!publishbookid || publishbookid == "0"){
      layer.open({
          content: "您还未发布本书，请到客户端APP发布此书，可以先备份此章节，发布本书后再发布章节。",
          btn:["知道了"]
      }); 
      return;
    }
    if(wordCount < 1000){
      layer.open({
          title: '提示',
          content: '章字数少于1000字，可能没法吸引读者，是否继续写？',
          btn: ['发布','继续写'],
          yes: function(index){
            tipViewStep();
            layer.close(index);
          },
          no:function(){
          }
      });      
    }else{
      tipViewStep();
    }
    function tipViewStep(){
      releaseTime = "";
      layer.open({
          title: '提示',
          content: '您检查完了吗，确定需要发布到书城吗？发布之前一定要预览检查一下有不有错误哦！ '+
          '<div style="text-align:left;margin-top:10px;font-size:10px;color:#999">'+
            '<label for="time-release">定时发布</label>'+
            '<input id="time-release" style="vertical-align: middle;" type="checkbox"/>：'+    
            '<input id="time-release-picker" style="display:none" type="text"/>'+
          '</div>',
          btn: ['预览','发布'],
          yes: function(index){
            $("#cp-view").trigger("click");
          },
          no:function(){
            //发布
            var pick = $("#time-release-picker");
            var checktime = $("#time-release");
            if(checktime[0].checked){
              if(pick.val()){
                releaseTime = pick.val();
                tipContinueStep();
              }else{
                layer.open({
                    content: '请选择发布时间',
                    time: 2
                });
              }
            }else{
              tipContinueStep();
            }

          }
      });
      bindtime();
      function bindtime(){
        setTimeout(function(){
          var pick = $("#time-release-picker");
          var checktime = $("#time-release");
          if(!pick[0]){
            bindtime();
            return;
          }
          //TODO
          checktime.on("change",function(){
            if(this.checked){
              pick.show().datetimepicker({
                minDate:'+1970/01/02',
                defaultTime:"00:00",
                step:30
              })
            }else{
              pick.hide().datetimepicker('destroy')
            }
          })

        },500)
      }

    }

    function tipContinueStep(){
      baseLoad();
      $.ajax({
        url:APIURL + "/Novel/getSensitiveWords.php",
        data:"userId=" + userId(),
        type:"post",
        success:function(data){
          hideBaseLoad();
          data = $.parseJSON(data);
          if(data.status != "FAILED"){
            var ssArr = data.value.split(";");
            var ssIncludArr = [];
            var str = tle + con;
            for(var i = 0, len = ssArr.length;i < len; i++){
              var ssWord = ssArr[i];
              var reg = new RegExp(ssWord,"i");
              if(reg.test(str)){
                ssIncludArr.push(ssWord)
              }
            }
            if(ssIncludArr.length){
              var ssTips = ssIncludArr.slice(0,6).join("  ");
              layer.open({
                title: '提示',
                content: '您的章节内容中含有  '+ssTips+'  等敏感词，可能会审核不通过，是否继续发布?',
                btn: ['嗯', '不要'],
                yes: function(index){
                  layer.close(index);
                  isCheckSetCoin();
                }
              })
            }else{
              isCheckSetCoin();
            }                
          }else{
            layer.open({
                content: data.value,
                time: 1
            }); 
          }

        },
        error:function(err){
          hideBaseLoad();
          layer.open({
              content: err.value || err_txt,
              time: 2
          });
        }
      })      
    }


  })

  function isCheckSetCoin(){
    if(editNum && editNum != "0"){
      checkSetCoin()
    }else{
      if(publishid > 0){
        layer.open({
            content: "本章修改次数已用尽，无法再重新发布到书城，请联系管理员。",
            btn:["知道了"]
        });        
      }else{
        checkSetCoin();
      }
 
    }
  }
  
  //检测是否可以收费
  function checkSetCoin(callback){
    baseLoad();
    $.ajax({
      url:APIURL + "/Novel/checkChapterCanSetCoin.php",
      data:"userId=" + userId() + "&bookId="+bookid,
      type:"get",
      success:function(data){
        hideBaseLoad();
        data = $.parseJSON(data);
        if(data.status != "FAILED"){
          if(!data.value || data.value == "0"){
            releaseChapter();
          }else{
            layer.open({
              title: '提示',
              content: '您可以设置收费阅读此章节 3阅币/1000字，共'+wordCount+'字,可赚得'+price+'阅币',
              btn: ['收费发布', '不收费发布'],
              yes: function(index){
                layer.close(index);
                var price = parseInt(wordCount/1000)*3;
                releaseChapter();
              },
              no:function(){
                releaseChapter()
              }
            })            
          }

        }else{
          layer.open({
              content: data.value,
              time: 1
          }); 
        }

      },
      error:function(err){
        hideBaseLoad();
        layer.open({
            content: err.value || err_txt,
            time: 2
        });
      }
    })
  }

  //发布到书城
  function releaseChapter(){
    var tle = encodeURIComponent(chapterTle.val());
    var con = encodeURIComponent(chapterCon.val());
    baseLoad();
    var publishChapterIdStr = "&publishChapterId="+publishid;
    if(!publishid || publishid == "0"){
      publishChapterIdStr = "";
    }

    //TODO 添加发布时间参数？？？   参数值 releaseTime
    var updata = "userId=" + userId() + "&remoteBookId="+bookid+"&publishBookId="+publishbookid+"&remoteId="+chapterid+
      "&title="+tle+"&content="+con+"&wordCount="+wordCount+
      "&orderId="+orderid+"&price="+price+"&submitUser="+userId()+publishChapterIdStr;
    $.ajax({
      url:APIURL + "/Novel/publishChapterWeb.php",
      data:updata,
      type:"post",
      success:function(data){
        hideBaseLoad();
        data = $.parseJSON(data);
        if(data.status != "FAILED"){
          changeEditNum(data.value.editCount);
          $(".bar-bread span").text(decodeURIComponent(tle));
          if(!chapterid){
            showDel();
            publishid = data.value.publishId;
            orderid = data.value.orderId;
            chapterid = data.value.remoteId;      
          } 
          layer.open({
              content: "已发布到书城",
              time: 1
          });
        }else{
          layer.open({
              content: data.value,
              time: 1
          }); 
        }

      },
      error:function(err){
        hideBaseLoad();
        layer.open({
            content: err.value || err_txt,
            time: 2
        });
      }
    })
  }

  //创建本地记录,每一秒记录一次
  chapterTle.on("focus",function(){
    recordEditNative()
  }).on("blur",function(){
    cancelRecordEditNative();
  })
  chapterCon.on("focus",function(){
    recordEditNative()
  }).on("blur",function(){
    cancelRecordEditNative();
  })
  function recordEditNative(){
    INTERVAL_EDIT_SAVE = setInterval(function(){
      localStorage.setItem("record_edit_param",'bookid='+bookid+'&chapterid='+chapterid+'&orderid='+orderid+'&publishid='+publishid+'&bookname='+bookname+'&chaptername='+encodeURIComponent(chaptername)+'&publishbookid='+publishbookid)
      localStorage.setItem( "record_tle",encodeURIComponent(chapterTle.val()) );
      localStorage.setItem( "record_con",encodeURIComponent(chapterCon.val()) );
      localStorage.setItem("record_type","edit");
    },1000)
  }
  function cancelRecordEditNative(){
    clearInterval(INTERVAL_EDIT_SAVE)
  }

  //缩进 TAB键缩进一个全角空格   回车键缩进两个全角空格
  set_tab_indent_for_textareas();

})